package 网络编程.Netty编程;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

class HeartBeatServerHandler extends SimpleChannelInboundHandler<MyNettyMsg> {
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("HeartBeatServerHandler的channelActive被调用");
		super.channelActive(ctx);
	}
	
	//如何直接发送对象呢?
	@Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    	
    	IdleStateEvent event = (IdleStateEvent)evt;
    	
    	IdleState idleState = event.state();
    	
    	//若是读空闲时间
    	if(IdleState.READER_IDLE == idleState ) {
    		System.out.println("触发了一次读空闲事件");
    		ctx.writeAndFlush(new MyNettyMsg("hello word fuck!!"));//flush
    	}
    	
    	if(IdleState.WRITER_IDLE == idleState ) {
    		System.out.println("触发了一次写空闲事件");
    	}
    	
        
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
    
	@Override
	protected void messageReceived(ChannelHandlerContext ctx, MyNettyMsg msg) throws Exception {
		System.out.println("接收到服务器发送的消息 : " +  msg.getContent());
	}
}
